package com.csu.common.wx;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.csu.common.constants.CommonParams;
import com.csu.common.constants.SystemCode;
import com.csu.common.exception.WebException;
import com.csu.common.utils.HttpUtil;
import com.csu.common.utils.JsonUtil;
import com.csu.common.utils.RedisUtil;
import com.csu.common.utils.SHA1Util;
import com.csu.common.utils.UUIDUtil;
import com.csu.common.vo.WxAccessSignTokenVo;
import com.csu.common.vo.WxJsapiTicketSignVo;
import com.csu.common.vo.WxJsapiTiketResultVo;

/**
 * @项目名称：cphone
 * @类名称：WxJsapiTiketHelper
 * @类描述：
 * @创建人：Tangc
 * @创建时间：2017年12月23日 上午9:44:38
 * @company:
 */
public class WxJsapiTiketHelper
{

    private static final Logger logger = Logger.getLogger(WxAuthorizeHelper.class);
    private static final String Access_Token = "JSAPI_REFESH_TOKEN";
    private static final String JSAPI_TIKET = "JSAPI_TIKET";

    private static String getAccessToken()
    {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("grant_type", "client_credential");
        params.put("appid", CommonParams.WX_APP_ID);
        params.put("secret", CommonParams.WX_APP_SECRET);

        String json = HttpUtil.getMap(CommonParams.WX_ACCESS_TOKEN_URL, params);
        logger.debug("获取Access_Token返回结果:" + json);
        WxAccessSignTokenVo accessTokenVo = JsonUtil.toObject(json, WxAccessSignTokenVo.class);

        String result = accessTokenVo.getAccess_token();
        RedisUtil.getRedisDb().setex(Access_Token, 7000, result);
        logger.debug("成功获取到Access_Token:" + result);
        return result;

    }

    /**
     * @description
     * @author TangC
     * @date 2017年12月23日 下午2:34:13
     * @param openid
     * @return
     * @throws WebException
     */
    private static String getJsapTiket() throws WebException
    {
        Map<String, Object> params = new HashMap<String, Object>();
        String accessToken = RedisUtil.getRedisDb().get(Access_Token);
        if (accessToken == null)
        {
            accessToken = getAccessToken();
        }
        params.put("access_token", accessToken);
        params.put("type", "jsapi");

        String json = HttpUtil.getMap(CommonParams.WX_JSAPI_TIKET_URL, params);
        logger.debug("获取jsapi_tiket返回结果:" + json);
        if (json == null)
        {
            logger.error("获取微信jsapi_tiket失败");
            throw new WebException(SystemCode.WX_JSAPI_Tiket_ERROR, "获取微信jsapi tiket失败");
        }
        WxJsapiTiketResultVo resultVo = JsonUtil.toObject(json, WxJsapiTiketResultVo.class);
        if (resultVo.getErrcode() != 0)
        {
            logger.error("获取微信jsapi_tiket失败");
            throw new WebException(SystemCode.WX_JSAPI_Tiket_ERROR, "获取微信jsapi tiket失败");
        }
        String ticket = resultVo.getTicket();
        logger.debug("成功获取到jsapi_tiket:" + ticket);
        RedisUtil.getRedisDb().setex(JSAPI_TIKET, 7000, ticket);
        return ticket;
    }

    public static WxJsapiTicketSignVo getJSapiTiketSign(String url) throws WebException
    {
        logger.debug("URL:"+url);
        String tiket = RedisUtil.getRedisDb().get(JSAPI_TIKET);
        if (tiket == null)
        {
            tiket = getJsapTiket();
        }
        String noncestr = UUIDUtil.getRandomStr();
        Long timestamp = System.currentTimeMillis();

        String jsapiTicketString = "jsapi_ticket=" + tiket + "&noncestr=" + noncestr + "&timestamp=" + timestamp
                + "&url=" + url;
        logger.debug("待签名串:" + jsapiTicketString);
        String signature = SHA1Util.SHA1(jsapiTicketString);
        logger.debug("签名得到signature:" + signature);
        WxJsapiTicketSignVo result = new WxJsapiTicketSignVo();
        result.setAppId(CommonParams.WX_APP_ID);
        result.setNonceStr(noncestr);
        result.setSignature(signature);
        result.setTimestamp(timestamp);
        return result;

    }
}
